<?php
namespace Rainrock\Framework\Controller;


use Rainrock\Framework\kernel\base\Rock;
use Rainrock\Framework\kernel\base\Request;
use Rainrock\Framework\kernel\base\Auth;
use Rainrock\Framework\kernel\base\CDate;
use Rainrock\Framework\kernel\base\Check;
use Rainrock\Framework\kernel\base\Web;
use Rainrock\Framework\kernel\base\Jiami;
use Rainrock\Framework\kernel\Html\HtmlBase;
use Rainrock\Framework\kernel\Html\HtmlLabel;
use Rainrock\Framework\kernel\Html\HtmlButton;
use Rainrock\Framework\kernel\Html\HtmlInput;
use Rainrock\Framework\kernel\Html\HtmlTextarea;
use Rainrock\Framework\kernel\Html\HtmlCheckbox;
use Rainrock\Framework\kernel\Html\HtmlSelect;
use Rainrock\Framework\kernel\Html\HtmlImage;
use Rainrock\Framework\kernel\core\Module;

/**
*	公共主录入页
*/
class InputController extends AuthModeController{
	
	
	/**
	*	录入页的
	*/
	public function indexAction()
	{
		$mid   	= $this->mid;
		$mode 	= $this->modeInfo;
		if(!$mode->getIsinput())return $this->backError('此模块没开启录入');
		
		$title  = $mode->getName();
		if($mid > 0){
			$title.='(编辑)';
		}else{
			$title.='(新增)';
		}
		
		$html 		= HtmlBase::get();
		$html->setTitle($title);
		$ismobile 	= Web::isMobile();
		$border		= 'var(--border)';
		
		$mdiv 		= HtmlLabel::get()->setAlign('left')->addCss('mainbody')->setId('maindiv');
		
		if(!$ismobile){
			$mdiv->addStyle('border',$border);
			$mdiv->setRadius(10);
			$mdiv->setMargin(10);
			$mdiv->setWidth(460);
		}else{
			$mdiv->addStyle('border-top',$border);
			$mdiv->addStyle('border-bottom',$border);
		}
		
		$farr	= $mode->getFields();
		$xuhao 	= 0;
		$farrs	= array();
		$upimg  = false;
		foreach($farr as $k=>$rs){
			if($rs['islu']==0)continue;
			$type 	= $rs['fieldstype'];
			$dbtype = $rs['dbtype'];
			$fid  	= $rs['fields'];
			$name  	= $rs['name'];
			$sm  	= $rs['sm'];
			$zdsm  	= $rs['zdsm'];
			$isbt  	= $rs['isbt'];
			
			$sdiv 	= HtmlLabel::get()->setAlign('left')->addCss('flex')->setPadding(15)->setId('div_'.$fid.'');
			if($isbt==1)$sdiv->addAttrs('required','true');
			
			$label	= HtmlLabel::get()->setAlign('right')->setPadding(10,'right')->setWidth(80);
			if($zdsm)$label->addCont(HtmlLabel::get('span')->addCont('?')->setOnclick('js.alert(\''.$zdsm.'\')')->addCss('cursor')->setPadding(3));
			if($isbt==1)$label->addCont(HtmlLabel::get('font')->addCont('*')->setFontcolor('red'));
			
			$label->addCont($name);
			$sdiv->addCont($label);
			
			$input	= HtmlInput::gets()->addStyle('flex',1)->setTishi($sm);
			if($type == 'textarea'){
				$input	= HtmlTextarea::gets()->addStyle('flex',1)->setTishi($sm);
			}else if($type == 'select'){
				$input	= HtmlSelect::gets()->addStyle('flex',1);
				$input->setData($mode->getData($rs['data']));
			}else if($type == 'checkbox'){
				$input	= HtmlCheckbox::gets()->setTishi($sm);
			}
			if(($type=='text' || $type=='number')&& $this->contain($dbtype,'int')){
				$input->setType('number');
				$input->addAttrs('onfoucs', 'js.focusval=this.value');
				$input->addAttrs('onblur', 'js.number(this)');
			}
			
			$input->setName($fid);
			if($mid==0){
				if(!$this->isempt($rs['dev']))$input->setValue($rs['dev']);
			}
			
			if($type == 'uploadimg'){
				$odiv = HtmlLabel::get()
					->addCont($input->setType('hidden')->setId(''.$fid.'_id'))
					->addCont(HtmlImage::gets()->setOnclick('js.viewimg(this)')->setId(''.$fid.'_id_img')->setSrc(''.URLSTATIC.'webstatic/images/noimg.jpg')->setWidth(100)->setHeight(100))
					->addBr()
					->addCont(
						HtmlLabel::get()->addCss('webbtn-group')->addCont(HtmlButton::gets()->setOnclick('input.uploadimg(\''.$name.'\',\''.$fid.'_id\')')->addCont('选择')->addCss('webbtn-default webbtn-mini'))
						->addCont(HtmlButton::gets()->setOnclick('input.uploadclear(\''.$fid.'_id\')')->addCont('x')->addCss('webbtn-default webbtn-mini'))
					);
				$input = $odiv;
				if(!$upimg)$html->addJse($this->c('rockfile')->importurl(), true);
				$upimg = true;
			}
			
			$cont = HtmlLabel::get()->addCont($input)->setAlign('left')->addStyle('flex',1)->addCss('flex');
			$sdiv->addCont($cont);
			if($xuhao>0)$sdiv->addStyle('border-top',$border);
			$mdiv->addCont($sdiv);
			
			$farrs[] = array(
				'fields' => $fid,
				'name' => $name,
				'isbt' => $rs['isbt'],
				'isjm' => $rs['isjm'],
				'fieldstype' => $type,
				'dbtype' 	 => $dbtype,
			);
			$xuhao++;
		}
				
		$html->addCont(HtmlLabel::get()->addCont($title)->setFontsize(20)->setMargin(20));
		$html->addCont(HtmlLabel::get('form')->setName('myform')->addAttrs('autocomplete','off')->addCont($mdiv));
		$btn = HtmlLabel::get()
			->setMargin('15px 10px')
			->addCont(
				HtmlButton::gets()->setValue('保存')->setWidth(120)->setonClick('input.save(this)')->setId('btnsave')
			);
		
		$html->addCont(HtmlLabel::get()->setId('msgview')->setMargin(10,'top'));		
		$html->addCont($btn);
		$html->addScript('var fieldsarr = '.json_encode($farrs).';');
		$html->addScript('var mid='.$mid.',modenum=\''.$mode->getNum().'\',modegroup=\''.$mode->getGroup().'\';');
		$html->addJse('input');
		return $html->show();
	}
	
	/**
	*	获取可编辑的数据
	*/
	public function dataeditAction()
	{
		$mode 	= $this->modeInfo;
		$mode->loadData($this->mid);
		$data   = $mode->getModel()->getone($this->mid);
		if(!$data)return $this->returnerror('记录不存在');
		unset($data['pass']);unset($data['id']);
		return $this->returnsuccess(array(
			'data' => $data
		));
	}
	
	/**
	*	保存数据
	*/
	public function saveAction()
	{
		$mid   	= $this->mid;
		$mode 	= $this->modeInfo;
		if(!$mode->getIsinput())return $this->returnerror('此模块没开启录入');
		
		$table  = $mode->getTable();
		$model 	= $this->m($table);
		$ors	= false;
		$isadd	= true;
		if($mid >0){
			$isadd 	= false;
			$ors 	= $model->getone($mid);
			if(!$ors)return $this->returnerror('记录不存在');
		}
		
		$farr	= $mode->getFields();
		$saveda	= array();
		foreach($farr as $k=>$rs){
			if($rs['islu']==0 || $rs['isfields']==0)continue;
			$fid = $rs['fields'];
			$val = Request::post($fid);
			$oval= ''.$val.'';
			if($rs['isjm']==1)$val = Jiami::base64encode($val);
			
			if($rs['isbt']==1 && $this->isempt($val))return $this->returnerror(''.$rs['name'].'不能为空');
			
			if($rs['isonly']==1 && !$this->isempt($val)){
				$to = $model->getCount("`{$fid}`='$val' AND `id`<>".$mid."");
				if($to >0 )return $this->returnerror(''.$rs['name'].'('.$oval.')已经存在了');
			}
			if(substr($rs['type'],0,4)=='date' && $this->isempt($val))$val = NULL;
			$saveda[$fid] = $val;
		}
		
		$allfields 	= $this->nDb->getAllFields($this->nDb->getDbperfix($table));
		$fiearr		= array();
		foreach($allfields as $k=>$rs)$fiearr[] = $rs['fields'];
		
		if(in_array('optdt', $fiearr) && !array_key_exists('optdt', $saveda))$saveda['optdt'] = CDate::now();
		if(in_array('uid', $fiearr) && !isset($saveda['uid']) && $isadd)$saveda['uid'] = Auth::$USERID;
		if(in_array('optname', $fiearr) && !isset($saveda['optname']))$saveda['optname'] = Auth::$NAME;
		if(in_array('optid', $fiearr) && !isset($saveda['optid']))$saveda['optid'] = Auth::$USERID;
		
		$barr  = $mode->mListener->onSaveBefore($saveda, $mid, $isadd);
		if($barr){
			if(is_string($barr))return $this->returnerror($barr);
			if(is_array($barr)){
				if(isset($barr['msg']))return $this->returnerror($barr['msg']);
				if(isset($barr['data'])){
					$bdata = $barr['data'];
					foreach($bdata as $k=>$v)$saveda[$k] = $v;
				}
				if(isset($barr['nosave'])){
					$nosave = $barr['nosave'];
					if(is_string($nosave))$nosave = explode(',', $nosave);
					foreach($nosave as $k)unset($saveda[$k]);
				}
			}
		}
		
		if($mid == 0){
			$mid = $model->insert($saveda);
		}else{
			$model->update($saveda, $mid);
		}
		
		if($this->nDb->isError)return $this->returnerror($this->nDb->error());
		
		$mode->mListener->onSaveAfter($saveda, $mid, $isadd);
		return $this->returnsuccess();
	}
	
	/**
	*	删除
	*/
	public function deleteAction()
	{
		$mode 		= $this->modeInfo;
		$ids		= Check::onlynumber(Request::get('ids'));
		if(!$ids)return $this->returnerror('idserror'); 
		$barr		= $mode->mListener->onDeleteBefore($ids);
		if($barr && is_string($barr))return $this->returnerror($barr);
		$this->m($mode->getTable())->delete('`id` in('.$ids.')');
		if($this->dbError(true))return $this->returnerror($this->dbError());
		$mode->mListener->onDeleteAfter();
		return $this->returnsuccess();
	}
	
	/**
	*	公共编辑保存的
	*/
	public function savecellAction()
	{
		$mode 		= $this->modeInfo;
		$id 		= Request::postint('id');
		$fields 	= Request::post('fieldname','', true);
		$value 		= Request::post('value');
		if(!$fields || !$id)return $this->returnerror('error');
		$mode->loadData($id);
		$barr		= $mode->mListener->onSavecellBefore($fields, $value);
		if($barr && is_string($barr))return $this->returnerror($barr);
		$this->m($mode->getTable())->update(array($fields => $value),$id);
		if($this->dbError(true))return $this->returnerror($this->dbError());
		$mode->mListener->onSavecellAfter($fields, $value);
		return $this->returnsuccess();
	}
	
	/**
	*	列表数据
	*/
	public function datalistAction()
	{
		$mode 	= $this->modeInfo;
		$sort 	= Request::get('sort');
		$dir  	= Request::get('dir');
		$loadci = Request::getint('loadci');
		$order  = '`id` DESC';
		$fields  = '*';
		$owhere = '';
		$bfarr	= $mode->mListener->onDataListBefore();
		if($bfarr && is_array($bfarr)){
			$order 	= $this->arrvalue($bfarr, 'order', $order);
			$fields = $this->arrvalue($bfarr, 'fields', $fields);
			$owhere = $this->arrvalue($bfarr, 'where');
		}
		if($bfarr && is_string($bfarr))$owhere = $bfarr;
		
		if($sort && $dir)$order = '`'.$sort.'` '.$dir.'';
		$fields_select  	= Request::get('fields_select');
		$fields_like  		= Request::get('fields_like');
		$key  				= Jiami::base64decode(Request::get('fields_keyword'));
		$barr 				= array();
		$store 				= array();
		$tfarr 				= array();
		$jfarr 				= array();
		$farr 				= $mode->getFields();
		
		$where  = '1=1';
		if($fields_select){
			$where = "`$fields_select`";
			if($fields_like=='like')$where.=" LIKE '%".$key."%'";
			if($fields_like=='deng')$where.=" = '".$key."'";
			if($fields_like=='denk')$where = "IFNULL(`$fields_select`,'')=''";
		}else{
			if($key){
				
			}
		}
		if($owhere)$where.=' AND '.$owhere.'';
		$obj  = $this->m($mode->getTable());
		$count= $obj->getCount($where);
		$rows = array();
		
		if($count > 0 || $loadci== 1){
			foreach($farr as $k=>$rs){
				if(($rs['islb']==1 || $rs['isss']==1)  && $rs['fieldstype']=='select'){
					$store[$rs['fields']] = $mode->getData($rs['data']);
					if($rs['islb']==1)$tfarr[] = $rs['fields'];
				}
				if($rs['islb']==1 && $rs['isjm']==1)$jfarr[$rs['fields']] = $rs;
			}
		}
		
		if($loadci== 1){
			$barr['fieldsarr']  = $farr;
			$barr['store'] 		= $store;
		}
		if($count > 0){
			if($store)foreach($store as $fid=>$srow){
				$sdata = array();
				foreach($srow as $k1=>$rs1)$sdata[$rs1['value']] = $rs1;
				$store[$fid] = $sdata;
			}
			$fun  = function($row, $can){
				$row = $can['ling']->onReplacers($row, 2);
				if($can['tfarr'])foreach($can['tfarr'] as $fid){
					$val = Rock::arrvalue($row, $fid);
					if(!isset($row[$fid.'_textcn']) && !Rock::isempt($val) && isset($can['store'][$fid])){
						if(isset($can['store'][$fid][$val])){
							$svrs = $can['store'][$fid][$val];
							if($svrs){
								$row[$fid.'_textcn'] = $svrs['name'];
								if(isset($svrs['color']))$row[$fid.'_color'] = $svrs['color'];
							}
						}
					}
				}
				$jfarr = $can['jfarr'];
				if($jfarr)foreach($jfarr as $fid=>$rs){
					$val = Rock::arrvalue($row, $fid);
					if($rs['isjm']==1 && !Rock::isempt($val)){
						$val = Jiami::base64decode($val);
						$row[$fid] = substr($val,0, 3).'****'.substr($val,-4);
					}
				}
				return $row;
			};
			$rows = $obj->getall($where, $fields, $order, 
				Request::getint('limit'), 
				Request::getint('page'), '', $fun, 
				array(
					'ling'	=> $mode->mListener,
					'store'	=> $store,
					'tfarr'	=> $tfarr,
					'jfarr'	=> $jfarr,
				)
			);
		}
		
		$barr['totalCount'] = $count;
		$barr['rows'] 		= $rows;
		$sbarr	= $mode->mListener->onDataListAfter($rows);
		if($sbarr && is_array($sbarr))foreach($sbarr as $k=>$v)$barr[$k] = $v;

		return $this->returnsuccess($barr);
	}
	
	/**
	*	公共列表显示
	*/
	public function listAction()
	{
		$div 	= HtmlLabel::get();
		$rand 	= Request::get('rand');
		$pnum 	= Request::get('pnum');
		$ismobile 	= Web::isMobile();
	
		$mdiv 	= HtmlLabel::get()->addCss('panel')->addStyle('padding','10px')->setAlign('left');
		if(!$ismobile)$mdiv->addCss('flex');
		
		if($this->modeInfo->getIsinput()){
			$mdiv->addCont(HtmlButton::gets()->addCont('新增')->setClickevt('add')->addStyle('margin-right','10px'));
		}
		$likea[] = array('value'=>'like','name'=>'包含');
		$likea[] = array('value'=>'deng','name'=>'等于');
		$likea[] = array('value'=>'denk','name'=>'等于空');

		$mdiv->addCont(
			HtmlLabel::get()->addCss(($ismobile) ? '' : 'webbtn-group')
			->addCont(HtmlSelect::gets()->setId('fields_select{rand}')->setData(array())->setWidth(150))
			->addCont(HtmlSelect::gets()->setValue('like')->setWidth(100)->setData($likea)->setId('fields_like{rand}'))
			->addCont(HtmlInput::gets()->setWidth(120)->setId('fields_keyword{rand}')->setTishi('输入关键词'))
			->addCont(HtmlButton::gets()->addCont('搜索')->addCss('webbtn-default')->setClickevt('search'))
		);
		
		$rightbtn = HtmlLabel::get()->addStyle('flex', 1)->setId('right_{rand}')->setAlign('right');
		//右边的按钮
		$btna = $this->modeInfo->mListener->onListRightbtn($pnum);
		if($btna)foreach($btna as $k=>$rs)$rightbtn->addCont($rs->setMargin(10,'right'));
		
		$rightbtn->addCont(HtmlButton::gets()->addCont('编辑')->setClickevt('edit')->setId('editbtn_{rand}')->setMargin(10,'right')->addAttrs('disabled','true'));
		$rightbtn->addCont(HtmlButton::gets()->addCont('删除')->setClickevt('del')->setId('delbtn_{rand}')->addCss('webbtn-danger')->addAttrs('disabled','true'));
		$mdiv->addCont($rightbtn);
		
		$div->addCont($mdiv);
		
		$mdiv = HtmlLabel::get()->addCss('panel')->addStyle('margin-top','10px')->setAlign('left');
		$mdiv->addCont(HtmlLabel::get()->addStyle('padding','10px')->setId('table_view{rand}'));
		$div->addCont($mdiv);
		
		$sbarr = $this->modeInfo->mListener->onListScript();
		if($sbarr){
			$script = HtmlLabel::get('script');
			$scrstr[]= 'var listparams_'.$rand.'={rock:true';
			foreach($sbarr as $k=>$v){
				if(is_array($v)){
					$scrstr[] = ','.$k.':'.json_encode($v).'';
				}else if(is_string($v)){
					$scrstr[] = ','.$k.':'.$v.'';
				}else if(is_object($v) && method_exists($v, 'show')){
					$scrstr[] = ','.$k.':'.$v->show().'';
				}
			}
			$scrstr[]= '}';
			$script->addCont(join('', $scrstr));
			$div->addCont($script);
		}

		return $div->show();
	}
	
	/**
	*	运行接口里的方法
	*/
	public function queryAction()
	{
		$act = Request::get('act');
		if(!$act)return $this->returnerror('error');
		if(!method_exists($this->modeInfo->mListener, $act))return $this->returnerror(''.$act.'方法不存在');
		return $this->modeInfo->mListener->$act();
	}
}